//
//  ZYCNewsBulletinDetailContentViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/9/8.
//

#import "ZYCNewsBulletinDetailContentViewController.h"
#import "ZYCNewsBulletinDetailWebCell.h"
#import "ZYCWisdomProtalDetailHeaderView.h"
#import "ZYCNewsBulletinBottomView.h"
#import "ZYCNewBulletinModel.h"
#import "SESSFileLookController.h"
#import "ZYCOnlinePreviewViewController.h"
#import "ZYCNoDataView.h"
#import "ZYCMessageRevokeView.h"
#import "ZYCNavigationController.h"
#import "ZYCTipView.h"

#define kCachePath  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]

@interface ZYCNewsBulletinDetailContentViewController ()<UITableViewDelegate,UITableViewDataSource,UIDocumentInteractionControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZYCWisdomProtalDetailHeaderView *headerView;
@property (nonatomic, strong) ZYCNewsBulletinBottomView *footerView;
@property (nonatomic, strong) ZYCNewBulletinModel *model;
@property (nonatomic, strong) ZYCNewsBulletinDetailWebCell *webCell;
@property (nonatomic, assign) CGFloat webHeight;
@property (nonatomic, strong) ZYCNoDataView *noDataView;
@property (nonatomic, strong) ZYCMessageRevokeView *revokeView;
@property (nonatomic, strong) ZYCTipView *tipView;
@end

@implementation ZYCNewsBulletinDetailContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"详情";
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;

    [self.headerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self.tableView);
        make.width.mas_equalTo(kScreenWidth);
    }];

    [self.tableView layoutIfNeeded];
    [self loadNewsBulletinDetail];

}

-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"]) {
        self.webHeight = self.webCell.webView.scrollView.contentSize.height;
//        NSLog(@"内容高度:%f",self.webHeight);
        [self.tableView reloadData];
    }
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.webCell) {
        ZYCNewsBulletinDetailWebCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCNewsBulletinDetailWebCell class]) forIndexPath:indexPath];
        self.webCell = cell;
    }
    return self.webCell;

}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  return self.webHeight;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}



#pragma mark - 网络请求
- (void)loadNewsBulletinDetail{
    NSDictionary *params = @{
        @"noticeId":self.noticeId
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_NewBulletinDetail requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                self.model = [ZYCNewBulletinModel yy_modelWithDictionary:responseObject[@"body"]];
                [self.webCell.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
                if ([self.model.contentType integerValue] == 2) {//富文本
                    [self.webCell.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.model.content]]];
                }else {// 指定url
                    [self.webCell.webView loadHTMLString:self.model.content baseURL:nil];
                }
                self.headerView.model = self.model;
                [self.tableView layoutIfNeeded];
                self.tableView.tableHeaderView = self.headerView;
                self.footerView.filesList = self.model.noticeFiles;
                self.footerView.frame = CGRectMake(0, 0, kScreenWidth, (self.model.noticeFiles.count+1) * 45);
                self.tableView.tableFooterView = self.footerView;
                self.tableView.hidden = NO;
                self.noDataView.hidden = YES;
                [self.tableView reloadData];

            }else if([responseObject[@"code"] integerValue] == kContentRevoke){
                self.tableView.hidden = YES;
                self.noDataView.hidden = YES;
                self.revokeView.hidden = NO;
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
                
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}



#pragma mark - private method
- (void)clickDownloadAction:(ZYCNoticeFileModel *)model{
 
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [kCachePath stringByAppendingPathComponent:model.fileName];
    if ([fileManager fileExistsAtPath:filePath]) {
        self.tipView.filePath = filePath;
        [self.tipView show];
    }else{
        [self download:model];
    }
}

// 打开附件
- (void)openAnnex:(NSURL *)filePath{
    if ([[filePath pathExtension] isEqualToString:@"xls"] || [[filePath pathExtension] isEqualToString:@"pptx"]) {
        UIDocumentInteractionController *documentController = [UIDocumentInteractionController
                                   interactionControllerWithURL:filePath];
        [documentController setDelegate:self];
        [documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
    }else{
        SESSFileLookController *vc = [[SESSFileLookController alloc] initWithFilePath:filePath];
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:vc animated:YES completion:nil];
    }
}

- (void)download:(ZYCNoticeFileModel *)model{
    NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],model.filePath];
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *task = [[URLManager sharedURLManager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//        NSLog(@"downloadProgress%f",1.0*downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        [MrjSVProgressHUD showWithStatus:@"下载中..."];
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *cachesPath = [kCachePath stringByAppendingPathComponent:model.fileName];
        return [NSURL fileURLWithPath:cachesPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (!error) {
            [MrjSVProgressHUD showSuccessWithStatus:@"下载成功"];
            [self openAnnex:filePath];
        }else{
            [MrjSVProgressHUD showErrorWithStatus:@"下载失败"];
            NSLog(@"下载成功%@",error);
        }
    }];
    [task resume];
}



#pragma mark - getters
- (ZYCTipView *)tipView {
    if (!_tipView) {
        ZYCWeakSelf
        _tipView = [[ZYCTipView alloc] initWithFrame:CGRectMake(0, 0, 280.0f, 155.0f)];
        _tipView.title = @"温馨提示";
        _tipView.content = @"是否打开文件?";
        _tipView.clickComfirmBlock = ^(NSString * _Nonnull filePath) {
            [weakSelf openAnnex:[NSURL fileURLWithPath:filePath]];
        };
        [self.navigationController.view addSubview:_tipView];
    }
    return _tipView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCNewsBulletinDetailWebCell class] forCellReuseIdentifier:NSStringFromClass([ZYCNewsBulletinDetailWebCell class])];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}

- (ZYCWisdomProtalDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZYCWisdomProtalDetailHeaderView alloc] initWithFrame:CGRectZero];
    }
    return _headerView;
}

- (ZYCNewsBulletinBottomView *)footerView {
    ZYCWeakSelf
    if (!_footerView) {
        _footerView = [[ZYCNewsBulletinBottomView alloc] initWithFrame:CGRectZero];
        _footerView.downloadBlock = ^(ZYCNoticeFileModel * _Nonnull model) {
            [weakSelf clickDownloadAction:model];
        };
    }
    return _footerView;
}

- (void)onlinePreView:(ZYCNoticeFileModel *)model{
    NSURL *filePath = [NSURL URLWithString:[NSString stringWithFormat:@"%@/zd-system-service%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],model.filePath]];
    ZYCOnlinePreviewViewController *vc = [[ZYCOnlinePreviewViewController alloc] initWithFilePath:filePath];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (ZYCNoDataView *)noDataView {
    if (!_noDataView) {
        _noDataView = [[ZYCNoDataView alloc] initWithFrame:self.tableView.frame];
        _noDataView.hidden = YES;
        [self.view addSubview:_noDataView];
    }
    return _noDataView;
}




- (ZYCMessageRevokeView *)revokeView {
    ZYCWeakSelf
    if (!_revokeView) {
        _revokeView = [[ZYCMessageRevokeView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _revokeView.hidden = YES;
        _revokeView.closeBlock = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
        [weakSelf.navigationController.view addSubview:_revokeView];
    }
    return _revokeView;
}


-(void) dealloc
{
    // 移除KVO 否则 EXC_BAD_ACCESS
    [self.webCell.webView.scrollView removeObserver:self forKeyPath:@"contentSize" context:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
